<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Virtual List</title>
    <style>
      /* styles.css */
      .virtual-list-container {
        height: 500px; /* 固定高度 */
        overflow-y: auto; /* 允许滚动 */
        border: 1px solid #ccc;
      }

      .virtual-list-wrapper {
        position: relative;
      }

      .virtual-list-item {
        position: absolute;
        width: 100%;
        height: 50px; /* 每个列表项的高度 */
        box-sizing: border-box;
        border-bottom: 1px solid #eee;
        display: flex;
        align-items: center;
        padding: 0 16px;
      }
    </style>
  </head>
  <body>
    <div class="virtual-list-container" id="container">
      <div class="virtual-list-wrapper" id="wrapper"></div>
    </div>
    <script>
      const container = document.getElementById('container');
      const wrapper = document.getElementById('wrapper');
      const itemHeight = 50; // 每个列表项的高度
      const totalItems = 1000; // 总列表项数量
      const visibleItemCount = 10; // 可见区域能显示的列表项数量
      let scrollTop = 0;
      const items = Array.from(
        { length: totalItems },
        (_, i) => `Item ${i + 1}`
      );
      wrapper.style.height = `${itemHeight * totalItems}px`;
      const renderItems = () => {
        const startIndex = Math.floor(scrollTop / itemHeight);
        const endIndex = Math.min(
          startIndex + visibleItemCount,
          items.length - 1
        );
        wrapper.innerHTML = '';
        items.slice(startIndex, endIndex + 1).forEach((item, index) => {
          const itemElement = document.createElement('div');
          itemElement.className = 'virtual-list-item';
          itemElement.style.transform = `translateY(${
            itemHeight * (startIndex + index)
          }px)`;
          itemElement.textContent = item;
          wrapper.appendChild(itemElement);
        });
      };
      renderItems();
      container.addEventListener('scroll', () => {
        scrollTop = container.scrollTop;
        renderItems();
      });
    </script>
  </body>
</html>
